package com.wyclabs.auth.web.service;


import com.wyclabs.api.UserResource;
import com.wyclabs.auth.common.SecurityUser;
import com.wyclabs.commons.response.UserResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * 用户信息获取实现
 * @author rs
 * @date 2019/10/17
 */
@Slf4j
@AllArgsConstructor
public class UserDetailServiceImpl implements UserDetailsService {

    private final UserResource userResource;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserResponse userResponse;
        try {
            userResponse = userResource.findByUserName(username).checkThrow();
        } catch (Exception e) {
            log.warn("认证异常：" + e.getMessage());
            throw new AuthenticationServiceException("系统繁忙，请稍后再试！");
        }
        if (userResponse == null || userResponse.getId() == null) {
            throw new UsernameNotFoundException("用户不存在！");
        }
        return new SecurityUser(userResponse);
    }
}
